<?php

require_once 'vendor/paragonie/sodium_compat/autoload.php';
require_once 'vendor/mustangostang/spyc/Spyc.php';
require_once 'vendor/autoload.php';
use MessagePack\MessagePack;

function generateId() {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < 5; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$p = sodium_hex2bin('544bb8c5a82c90747b09c1d584166978deaf0789ed1a9bb4487b1d8e8e2ce7e6');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $req = file_get_contents('php://input');
    try{
        $value = MessagePack::unpack($req);
    } catch(Exception $e) {
        http_response_code(400);
        die();
    }

    $sig = $value['signature'];
    $msg = $value['url'];
    $v = sodium_crypto_sign_verify_detached($sig, $msg, $p);
    if ($v == True) {
        if (!file_exists('ids.yml'))
            $ids = [];
        else
            $ids = Spyc::YAMLLoad('ids.yml');

        $present = array_search($msg, $ids);
        if ($present !== false) {
            echo("https://apiote.tk/s/$present");
            die();
        }

        do {
            $id = generateId();
        } while (array_key_exists($id, $ids));
        $ids[$id] = $msg;
        $idsContent = Spyc::YAMLDump($ids);
        file_put_contents('ids.yml', $idsContent);
        http_response_code(200);
        echo("https://apiote.tk/s/$id");
    } else {
        http_response_code(403);
        die();
    }
} else {
    $actual_link = "$_SERVER[REQUEST_URI]";
    $a = explode('/', $actual_link);
    $id = end($a);
    $ids = Spyc::YAMLLoad('ids.yml');
    $url = $ids[$id];
    
    if (strpos($url, 'http') !== 0) {
        $url = "http://$url";
    }
    header("Location: $url");
}

?>
